package com.fantaike.algorithm.linear;

import java.util.Iterator;

/**
 * 队列：先进先出
 * @author jishushen
 * @create 2021-09-17 21:25
 */
public class Queue<T> implements Iterable<T>{
    //记录首结点
    private final Node<T> head;
    //当前栈的元素个数
    private int N;
    //记录最后一个结点
    private Node<T> last;

    public Queue(){
        this.head = new Node<>(null,null);
        this.last = null;
        this.N = 0;
    }


    private static class Node<T>{
        public T item;
        public Node<T> next;
        public Node(T item, Node<T> next) {
            this.item = item;
            this.next = next;
        }
    }
    //判断队列是否为空，是返回true，否返回false
    public boolean isEmpty(){
        return N == 0;
    };

    //获取队列中元素的个数
    public int size(){
        return this.N;
    };
    //从队列中拿出一个元素
    public T dequeue(){
        if (isEmpty()){
            return null;
        }
        Node<T> oldFirst = head.next;
        //删除就是让头结点的下一个节点指向下下节点
        head.next = oldFirst.next;
        //元素个数减一
        N--;

        //出队列其实就是删除元素，因此如果队列中的元素被删除完了，需要将last置为null
        if (isEmpty()){
            last = null;
        }
        return oldFirst.item;
    };

    //往队列中插入一个元素
    public void enqueue(T t){
        //1.判断last是否为空，为空说明是第一次插入
        if (last == null){
            //创建一个新的节点，赋值给last
            last = new Node<>(t,null);
            //让头结点的下一个指向laast
            head.next = last;
        }else {
            //进入这里说明不是第一次进入
            Node<T> oldNode = last;
            last = new Node<>(t,null);
            oldNode.next = last;
        }
        //让元素个数加1
        N++;
    }

    @Override
    public Iterator<T> iterator() {
        return new QIterator();
    }

    private class QIterator implements Iterator<T>{
        private Node<T> n;
        private QIterator() {
            n = head;
        }
        @Override
        public boolean hasNext() {
            return n.next != null;
        }
        @Override
        public T next() {
            n = n.next;
            return n.item;
        }
    }
}
